/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CoInsertFrame.java
 *
 * Created on 29/11/2011, 23:11:54
 */

package proj5labbd.graphics.comercial;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

/*
 * Painel de inserção de dados referentes à Comercial
 */
public class CoInsertPanel extends OperationPanel {

    /** Creates new form CoInsertFrame */
    public CoInsertPanel(ComercialFrame frame, DBInterface dbInterface) {
        super(frame,dbInterface);
        initComponents();
        jbtInsert.addActionListener(new ComercialAction());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnInsert = new javax.swing.JPanel();
        jlbTitulo = new javax.swing.JLabel();
        jtxtTitulo = new javax.swing.JTextField();
        jlbDesc = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtxaDesc = new javax.swing.JTextArea();
        jlbDept = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtbInsert = new javax.swing.JTable();
        jbtInsert = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Inserção"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnInsert.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros de inserção"));

        jlbTitulo.setText("Título");

        jlbDesc.setText("Descrição");

        jtxaDesc.setColumns(20);
        jtxaDesc.setRows(5);
        jScrollPane1.setViewportView(jtxaDesc);

        jlbDept.setText("Departamento");

        jtbInsert.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(jtbInsert);

        javax.swing.GroupLayout jpnInsertLayout = new javax.swing.GroupLayout(jpnInsert);
        jpnInsert.setLayout(jpnInsertLayout);
        jpnInsertLayout.setHorizontalGroup(
            jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnInsertLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE)
                    .addComponent(jlbTitulo)
                    .addComponent(jlbDesc)
                    .addComponent(jlbDept)
                    .addComponent(jtxtTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE))
                .addContainerGap())
        );
        jpnInsertLayout.setVerticalGroup(
            jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnInsertLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jlbTitulo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtxtTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jlbDesc)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jlbDept)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jbtInsert.setText("Inserir");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jpnInsert, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addComponent(jbtInsert, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpnInsert, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jbtInsert))
        );
    }// </editor-fold>//GEN-END:initComponents

    //Ativado quando o o painel é visualizado
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
            Logger.getLogger(CoInsertPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_formComponentShown

    //Ativado quando há um click no form
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtbInsert.clearSelection();
    }//GEN-LAST:event_formMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jbtInsert;
    private javax.swing.JLabel jlbDept;
    private javax.swing.JLabel jlbDesc;
    private javax.swing.JLabel jlbTitulo;
    private javax.swing.JPanel jpnInsert;
    private javax.swing.JTable jtbInsert;
    private javax.swing.JTextArea jtxaDesc;
    private javax.swing.JTextField jtxtTitulo;
    // End of variables declaration//GEN-END:variables

    //Inicia a(s) tabela(s) utilizada(s) no painel
    private void setupTable() throws SQLException {
            String[] data = {"idDe", "nomeDe"};
            String[] title = {"ID", "Nome do departamento"};
            String[] table = {"departamento"};
            DefaultTableModel model = new DefaultTableModel(dbInterface.view(data, null, table), title);
            jtbInsert.setModel(model);
            jtbInsert.setRowSelectionAllowed(true);
    }
    
    //Classe com ações tomadas pelo botão de inserção
    class ComercialAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {

            if (e.getSource() == jbtInsert) {

                if ( jtbInsert.getSelectedRowCount() == 1 && jtxtTitulo.getText().trim() != "") {
                    ArrayList<String> params = new ArrayList<String>();
                    ArrayList<String> fields = new ArrayList<String>();

                    params.add("SEQ_PROGRAMA_IDPR.NEXTVAL");
                    fields.add("idPr");
                    params.add("'"+jtxtTitulo.getText()+"'");
                    fields.add("tituloPr");

                    if (jtxaDesc.getText() != "") {
                        params.add("'"+jtxaDesc.getText()+"'");
                        fields.add("descricaoPr");
                    }

                    params.add((String)jtbInsert.getValueAt(jtbInsert.getSelectedRow(), 0));
                    fields.add("idDe");

                    String [] paramArray = new String[params.size()];
                    String [] fieldArray = new String[fields.size()];

                    params.toArray(paramArray);
                    fields.toArray(fieldArray);
                    try {
                        dbInterface.insert(fieldArray, paramArray, new String[]{"comercial"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Erro ao tentar inserir a tupla.");
                    }

                }
                else if (jtbInsert.getSelectedRowCount() != 1) {
                    JOptionPane.showMessageDialog(null, "Você deve escolher um departamento.");
                }
                else if (jtxtTitulo.getText().trim() == "") {
                    JOptionPane.showMessageDialog(null, "Você deve inserir o titulo do comercial.");
                }

            }

            }

        }


}
